from django.shortcuts import render
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView,RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from . import constants

from .models import User
from . import serializers
# Create your views here.


class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址增删改查
    """
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        # 判断用户地址数量是否超过上线
        # count = Address.objects.filter(user=request.user).count()
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        # return Response(serializer.data, status=status.HTTP_201_CREATED)

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)




class EmailView(UpdateAPIView):
    """添加更新邮箱"""
    serializer_class = serializers.EmailSerializer
    permission_classes = [IsAuthenticated]


    def get_object(self):
        return self.request.user


#url(r'^user/$',views.UserDetailView.as_view())
class UserDetailView(RetrieveAPIView):
    """个人中心基本信息"""
    #制定序列化器类
    serializer_class = serializers.UserDetailSerializer
    #指定限制，只有登陆用户访问
    permission_classes = [IsAuthenticated]
    #指定查询集
    # queryset =
    def get_object(self):
        return self.request.user



# url(r'^users/$', views.UserView.as_view()),
class UserView(CreateAPIView):
    """注册"""

    #指定序列华器
    serializer_class = serializers.UserSerializer





#判断用户是否存在
#usernames/(?P<username>\w{5,20})/count/
class UsernameCountView(APIView):
    """判断用户是否存在"""

    def get(self,request,username):
        #查询username作为条件查询该记录是否存在
        count = User.objects.filter(username = username).count()

        #序列化
        data ={
            'username':username,
            "count":count
        }

        #返回响应
        return Response(data)

#mobiles/(?P<mobile>1[3-9]\d{9})/count
class MobileCountView(APIView):
    """判断手机号是否存在"""

    def get(self, request, mobile):
        # 查询mobile作为条件查询该记录是否存在
        count = User.objects.filter(mobile=mobile).count()

        # 序列化
        data = {
            'username': mobile,
            "count": count
        }

        # 返回响应
        return Response(data)